﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using Model;
using DevExpress.Utils;
using DevExpress.XtraEditors;
using MainApp.Helper;
using BLL;
using View;
using System.Threading;
using System.Linq.Expressions;
using System.Threading.Tasks;
using DevExpress.Data;

namespace MainApp.Forms
{
    public partial class FormPersonList : XtraForm, IChildForm
    {
        List<Person> items = null;
        DataContext context = new DataContext();
        FormPerson formPerson = new FormPerson();
        int totalPageCount = 0;
        int pageIndex = 1;
        int pageSize = 20;
        int recordCount = 0;
        public FormPersonList()
        {
            InitializeComponent();

        }

        private void FormCateogory_Load(object sender, EventArgs e)
        {
            context.DataRepertory.Configuration.LazyLoadingEnabled = false;
            loadData();
            this.cmbPageSize.SelectedIndex = 0;
            this.txtPageIndex.Text = "1";
            //btnSearch_Click(null, null);
            this.txtPageIndex.TextChanged += this.txtPageIndex_TextChanged;
            this.cmbPageSize.EditValueChanged += this.cmbPageSize_EditValueChanged;
        }

        private void loadData()
        {
            var areas = context.DataRepertory.Areas.ToList();
            var nations = context.DataRepertory.Nations.ToList();
            var professions = context.DataRepertory.Professions.ToList();
            var politicalStatus = context.DataRepertory.PoliticalStatuses.ToList();
            var relations = context.DataRepertory.Relations.ToList();
            areas.ForEach(x =>
            {
                x.FullPathName = x.Name;
                var area = x;
                while (area.ParentID != Guid.Empty)
                {
                    var parent = areas.FirstOrDefault(w => w.ID == area.ParentID);
                    if (parent == null) { break; }
                    x.FullPathName = parent.Name + x.FullPathName;
                    area = parent;
                }
            });
        }

        public OperationResult Save()
        {
            this.gridView1.CloseEditor();

            return new OperationResult { Success = true };
        }

        public OperationResult Delete()
        {
            //var indexs = this.gridView1.GetSelectedRows();
            //List<Nation> deleteList = new List<Nation>();
            //foreach (int i in indexs)
            //{
            //    deleteList.Add(professionList[this.gridView1.GetDataSourceRowIndex(i)]);
            //}

            //return DataContext.DeleteNations(deleteList);
            return new OperationResult { Success = true };
        }

        public OperationResult RefreshData()
        {
            btnRefresh_Click(null, null);
            return new OperationResult(true);
        }

        private void gridView1_ValidateRow(object sender, DevExpress.XtraGrid.Views.Base.ValidateRowEventArgs e)
        {
            Person view = e.Row as Person;
            if (string.IsNullOrEmpty(view.Name))
            {
                e.Valid = false; e.ErrorText += "名称不能为空！"; return;
            }
            else
            {
                if (view.Name.Length > 50)
                {
                    e.Valid = false; e.ErrorText += "名称长度不能超过50！"; return;
                }
            }

            e.Valid = true;
        }

        private void FormPersonList_FormClosed(object sender, FormClosedEventArgs e)
        {
        }

        private void btnSearch_Click(object sender, EventArgs e)
        {
            Program.StartProgress();
            this.Enabled = false;

            var task = Task.Factory.StartNew(() =>
            {
                List<Expression<Func<Person, bool>>> queryWhereList = new List<Expression<Func<Person, bool>>>();
                if (!string.IsNullOrEmpty(this.txtKey.Text))
                {
                    queryWhereList.Add(x => x.Name.Contains(this.txtKey.Text) || x.PIN.Contains(this.txtKey.Text));
                }

                if (this.dateBegin.EditValue != null)
                {
                    queryWhereList.Add(x => x.Birthday >= dateBegin.DateTime);
                }
                if (this.dateEnd.EditValue != null)
                {
                    queryWhereList.Add(x => x.Birthday <= dateEnd.DateTime);
                }

                try
                {

                    if (this.gridView1.SortedColumns.Count == 0)
                    {
                        items = context.DataRepertory.GetPagedEntities<Person, string>(pageIndex, pageSize, out recordCount, x => x.Name, queryWhereList.ToArray()).ToList();
                    }
                    else
                    {
                        bool asc = this.gridView1.SortedColumns[0].SortOrder == ColumnSortOrder.Ascending;
                        switch (this.gridView1.SortedColumns[0].FieldName)
                        {

                            case "PIN":
                                items = context.DataRepertory.GetPagedEntities<Person, string>(pageIndex, pageSize, out recordCount, x => x.PIN, asc, queryWhereList.ToArray()).ToList();
                                break;
                            case "Birthday":
                                items = context.DataRepertory.GetPagedEntities<Person, DateTime>(pageIndex, pageSize, out recordCount, x => x.Birthday, asc, queryWhereList.ToArray()).ToList();
                                break;
                            case "Address":
                                items = context.DataRepertory.GetPagedEntities<Person, string>(pageIndex, pageSize, out recordCount, x => x.Address, asc, queryWhereList.ToArray()).ToList();
                                break;
                            case "Area.FullPathName":
                                items = context.DataRepertory.GetPagedEntities<Person, Guid>(pageIndex, pageSize, out recordCount, x => x.AreaID, asc, queryWhereList.ToArray()).ToList();
                                break;
                            case "Nation.Name":
                                items = context.DataRepertory.GetPagedEntities<Person, long>(pageIndex, pageSize, out recordCount, x => x.NationID, asc, queryWhereList.ToArray()).ToList();
                                break;
                            case "Profession.Name":
                                items = context.DataRepertory.GetPagedEntities<Person, long>(pageIndex, pageSize, out recordCount, x => x.ProfessionID, asc, queryWhereList.ToArray()).ToList();
                                break;
                            case "SexName":
                                items = context.DataRepertory.GetPagedEntities<Person, SexEnum>(pageIndex, pageSize, out recordCount, x => x.Sex, asc, queryWhereList.ToArray()).ToList();
                                break;
                            default:
                                items = context.DataRepertory.GetPagedEntities<Person, string>(pageIndex, pageSize, out recordCount, x => x.Name, asc, queryWhereList.ToArray()).ToList();
                                break;
                        }
                    }

                    this.Invoke(new Action(() =>
                    {
                        this.gridView1.StartSorting -= this.gridView1_StartSorting;
                        this.entityViewBindingSource.DataSource = null;
                        this.entityViewBindingSource.DataSource = items;
                        this.gridView1.StartSorting += this.gridView1_StartSorting;
                        UpdatePageData();
                        Program.StopProgress();
                        this.Enabled = true;
                        this.Refresh();
                    }));
                }
                catch (Exception ex)
                {
                    Program.ShowMessageDialog("查询数据时出错", ex.Message, ex.StackTrace);
                }
            });
        }

        private void btnRefresh_Click(object sender, EventArgs e)
        {
            btnSearch_Click(null, null);
        }

        private void btnFirst_Click(object sender, EventArgs e)
        {
            txtPageIndex.Text = "1";
            btnSearch_Click(null, null);
        }

        private void btnPrevious_Click(object sender, EventArgs e)
        {
            pageIndex--; txtPageIndex.Text = pageIndex + "";
            btnSearch_Click(null, null);
        }

        private void btnNext_Click(object sender, EventArgs e)
        {
            pageIndex++; txtPageIndex.Text = pageIndex + "";
            btnSearch_Click(null, null);
        }

        private void btnLast_Click(object sender, EventArgs e)
        {
            pageIndex = totalPageCount; txtPageIndex.Text = pageIndex + "";
        }

        private void txtPageIndex_TextChanged(object sender, EventArgs e)
        {
            if (int.TryParse(txtPageIndex.Text, out pageIndex))
            {
                if (pageIndex < 1) { pageIndex = 1; }
                if (pageIndex > totalPageCount) { pageIndex = totalPageCount; }
                btnSearch_Click(null, null);
            }
            else
            {
                MessageBox.Show("页码错误，请重新输入！"); this.txtPageIndex.SelectAll(); this.txtPageIndex.Focus();
            }
        }

        private void cmbPageSize_EditValueChanged(object sender, EventArgs e)
        {
            if (this.cmbPageSize.EditValue != null && int.TryParse(this.cmbPageSize.EditValue.ToString(), out pageSize))
            {
                btnSearch_Click(null, null);
            }
            else
            {
                this.cmbPageSize.SelectedIndex = 0;
            }
        }

        private void UpdatePageData()
        {
            this.labRecordCount.Text = recordCount.ToString();
            totalPageCount = recordCount / pageSize;
            if (recordCount % pageSize > 0)
            {
                totalPageCount++;
            }
            this.labPageCount.Text = totalPageCount.ToString();
            if (pageIndex >= totalPageCount)
            {
                this.btnNext.Enabled = false;
                this.btnLast.Enabled = false;
                pageIndex = totalPageCount;
            }
            else
            {
                this.btnNext.Enabled = true;
                this.btnLast.Enabled = true;
            }

            if (pageIndex == 1)
            {
                this.btnFirst.Enabled = false;
                this.btnPrevious.Enabled = false;
            }
            else
            {
                this.btnFirst.Enabled = true;
                this.btnPrevious.Enabled = true;
            }

            this.txtPageIndex.Text = pageIndex.ToString();
        }

        private void gridView1_StartSorting(object sender, EventArgs e)
        {
            btnSearch_Click(null, null);
        }

        private void gridView1_DoubleClick(object sender, EventArgs e)
        {
            if (this.gridView1.FocusedRowHandle > -1)
            {
                var model = items[this.gridView1.GetDataSourceRowIndex(this.gridView1.FocusedRowHandle)];
                if (formPerson.ShowDialog(model, context) == DialogResult.OK)
                {
                    btnSearch_Click(null, null);
                }
            }
        }
    }
}
